package com.heima.search.listener;

import com.alibaba.fastjson.JSON;
import com.heima.common.constants.ArticleConstants;
import com.heima.model.search.vos.SearchArticleVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;


/**
 * @Author ItZheng
 * @Date 2023/6/18 19:15
 * @Version 1.5
 * 虚拟机内存不足！！
 */
@Component
@Slf4j
public class SyncArticleListener {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @KafkaListener(topics = ArticleConstants.ARTICLE_ES_SYNC_TOPIC)
    public void onMessage(String message) {
        //参数校验：
        if (StringUtils.isNotEmpty(message)) {
            //反序列化：
            SearchArticleVo searchArticleVo = JSON.parseObject(message, SearchArticleVo.class);

            //加入索引库：
            //指定：索引库名称：
            IndexRequest indexRequest = new IndexRequest("app_info_article");
            indexRequest.id(searchArticleVo.getId().toString());
            //kafka信息本身就是json类型，可以直接用
            indexRequest.source(message, XContentType.JSON);

            //发送请求：
            try {
                restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
                log.info("添加ES成功");
            } catch (Exception e) {
                e.printStackTrace();
                log.info("添加ES失败");
            }
        }
    }
}
